<?php

namespace App\Http\Controllers;

use App\Models\Device;
use App\Models\DeviceGroup;
use App\Models\DeviceGroupAdd;
use App\Models\LogPhone;
use App\Models\ManagerLog;
use App\Models\Qq;
use App\Models\User;
use App\Models\WechatId;
use File;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Response;
use ClassesWithParents\F;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use Mockery\Exception;
use Validator;
use App\Models\Fans;
use Illuminate\Support\Facades\DB;

class FansController extends Controller
{
  public function index(Request $request)
  {
    if(!$request->type){
        $totalCount = Fans::count();
        $usedCount = Fans::where('is_used', true)->count();
        $maleCount = Fans::where('sex', '1')->count();
        $femaleCount = Fans::where('sex', '0')->count();
        $fans = Fans::where('name','like','%'. $request->name .'%')
            ->where('phone','like','%'. $request->phone .'%')
            ->select('id','name','phone','sex','is_used','is_certification')
            ->paginate(10)
            ->toArray();
    }else{
        $totalCount = Fans::where('type', $request->type)->count();
        $usedCount = Fans::where('type', $request->type)->where('is_used', true)->count();
        $maleCount = Fans::where('type', $request->type)->where('sex', '1')->count();
        $femaleCount = Fans::where('type', $request->type)->where('sex', '0')->count();
        $fans = Fans::where('type', $request->type)
            ->where('name','like','%'. $request->name .'%')
            ->where('phone','like','%'. $request->phone .'%')
            ->paginate(10)
            ->toArray();
    }
    $fans['totalCount'] = $totalCount;
    $fans['usedCount'] = $usedCount;
    $fans['maleCount'] = $maleCount;
    $fans['femaleCount'] = $femaleCount;
    return $this->success(0, '请求成功', $fans);
  }

  public function getPhone(){
      DB::beginTransaction();
      $phone_get_num = User::first()->phone_get_num;
      $fans = Fans::where('is_used', false)
          ->select('id','name','phone','sex')
          ->limit($phone_get_num)->lockForUpdate()->get();
      if($fans){
          foreach ($fans as $fan) {
              $fan->is_used = 1;
              $fan->save();
              unset($fan->is_used);
              unset($fan->updated_at);
          }
      }
      DB::commit();
      return $this->success(0, '请求成功', $fans);
  }

  public function qq(Request $request){
      $validator = Validator::make($request->all(), [
          'id' => 'sometimes|required|exists:qq,id'
      ]);
      if ($validator->fails()) {
          return $this->failure(-1, $validator->errors()->first());
      }
      if($request->id){
          Qq::destroy($request->id);
          return $this->success(0, '删除成功');
      }
      if($request->device_group_id > 0) {
          $query = Qq::where('qq_group_id', $request->device_group_id);
          $qq = $query->where('qq_pwd','like','%'. $request->qq_pwd .'%')
              ->paginate(10)
              ->toArray();
          $totalCount = $query->count();
          $usedCount = $query->where('is_used', true)->count();
      }else{
          $qq = Qq::where('qq_num','like','%'. $request->qq_num .'%')
              ->where('qq_pwd','like','%'. $request->qq_pwd .'%')
              ->paginate(10)
              ->toArray();
          $totalCount = Qq::count();
          $usedCount = Qq::where('is_used', true)->count();
      }
      $qq['totalCount'] = $totalCount;
      $qq['usedCount'] = $usedCount;
      return $this->success(0, '请求成功', $qq);
  }

    public function resetQQ($id){
        $qq = Qq::findOrFail($id);
        if($qq){
            if($qq->error_password_num < 20){
                $qq->is_used = 0;
                $qq->save();
            }
        }
        return $this->success(0, '',null);
    }

    public function qqErrorPassword($id){
        $qq = Qq::findOrFail($id);
        if($qq){
            $qq->error_password_num += 1;
            $qq->save();
        }
        return $this->success(0, '',null);
    }


  public function qqComment(Request $request){
      $validator = Validator::make($request->all(), [
          'id' => 'sometimes|required|exists:qq,id'
      ]);
      if ($validator->fails()) {
          return $this->failure(-1, $validator->errors()->first());
      }
      $query = Qq::findOrFail($request->id);
      if(isset($request->comment)){
          if($request->comment){
              $query->comment = $request->comment;
          }else{
              $query->comment = null;
          }
      }
      if(isset($request->phone_check)){
          if($request->phone_check){
              $query->phone_check = $request->phone_check;
          }else{
              $query->phone_check = null;
          }
      }
      $query->save();
      return $this->success(0, '关联缓存修改成功',$query);
  }

  public function setQQGroup(Request $request)
  {
      $validator = Validator::make($request->all(), [
          'id' => 'required|exists:qq,id',
          'device_group_id' => 'required|exists:device_groups,id',
      ]);
      if($validator->fails()) {
          return $this->failure(-1, $validator->errors()->first());
      }
      $qq = Qq::find($request->id);
      $qq->qq_group_id = $request->device_group_id;
      $qq->save();
      return $this->success(0, '', $qq);
  }

  public function getQq(Request $request){
      $validator = Validator::make($request->all(), [
          'device_id' => 'required|exists:devices,id',
      ]);
      if ($validator->fails()) {
          return $this->failure(-1, $validator->errors()->first());
      }
      DB::beginTransaction();
      $qq_group_id = Device::find($request->device_id)->device_group_id;
      $qq = Qq::where('qq_group_id', $qq_group_id)->where('is_used', 0)
          ->select('id','qq_num','qq_pwd','comment','is_used','is_exception','phone_check')
          ->lockForUpdate()->first();
      if($qq){
          $qq->is_used = 1;
          $qq->save();
      }else{
          $qq = Qq::where('qq_group_id', $qq_group_id)->where('error_password_num', '<', 20)->select('id')->get();
          foreach ($qq as $row){
              $data = Qq::findOrFail($row->id);
              $data->is_used = 0;
              $data->is_exception = 0;
              $data->save();
          }
          $qq = Qq::where('qq_group_id', $qq_group_id)->where('is_used', 0)->select('id','qq_num','qq_pwd','comment','is_used','is_exception','phone_check')->first();
          if($qq){
              $qq->is_used = 1;
              $qq->save();
          }else
              return $this->failure(-1, 'no data');
      }
      DB::commit();
      return $this->success(0, '请求成功', $qq);
  }

  public function getOne(Request $request)
  {
    $validator = Validator::make($request->all(), [
        'type' => 'required|numeric',
        'device_id' => 'sometimes|required|exists:devices,id',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    DB::beginTransaction();
    $fans = Fans::where(['is_used' => 0, 'type' => $request->type])->lockForUpdate()->first();
    if($request->type == 1) $detail_type = 5;
    else $detail_type = 2;
    $this->deviceDetailedList($type=1,$detail_type,$request->device_id);
    if ($fans) {
        if($fans->is_used == 0){
            $fans->is_used = 1;
            $fans->save();
            $data = $fans->toArray();
            DB::commit();
            if(Fans::find($fans->id)->is_used == 0) Log::info($fans->phone);
            return $this->success(0, 'OK', $data);
        }else{
            Log::info('is_used != 0 '.$fans->phone);
            return $this->failure(-1, 'no data');
        }
    }else{
        DB::commit();
        return $this->failure(-1, 'no data');
    }
  }

  public function setSex(Request $request, $fans_id)
  {
    $validator = Validator::make($request->all(), [
      'sex' => 'required|numeric',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $data = $request->only('sex');
    $fans = Fans::find($fans_id);
    if ($fans) {
      $fans->sex = $data['sex'];
      $fans->save();
      return $this->success(0, '更新成功', $fans);
    }
    return $this->failure(0, '没有找到粉丝数据');
  }

  public function setExists(Request $request, $fans_id)
  {
    $validator = Validator::make($request->all(), [
      'is_exists' => 'required|boolean',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $data = $request->only('is_exists');
    $fans = Fans::find($fans_id);
    if ($fans) {
      $fans->is_exists = $data['is_exists'];
      $fans->save();
      return $this->success(0, '更新成功', $fans);
    }
    return $this->failure(0, '没有找到粉丝数据');
  }

  public function setCertification(Request $request, $fans_id)
  {
    $validator = Validator::make($request->all(), [
      'is_certification' => 'required|boolean',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $data = $request->only('is_certification');
    $fans = Fans::find($fans_id);
    if ($fans) {
      $fans->is_certification = $data['is_certification'];
      $fans->save();
      return $this->success(0, '更新成功', $fans);
    }
    return $this->failure(0, '没有找到粉丝数据');
  }

  public function setUsed(Request $request, $fans_id)
  {
    $validator = Validator::make($request->all(), [
      'used' => 'required|boolean',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $data = $request->only('used');
    $fans = Fans::find($fans_id);
    if ($fans) {
        if($fans->is_exception == 0 && env('DB_DATABASE') != 'k3.wztx.com'){
            $fans->is_used = $data['used'];
            $fans->is_exception = 1;
            $fans->save();
        }
      return $this->success(0, '更新成功', $fans);
    }
    return $this->failure(0, '没有找到粉丝数据');
  }
  public function setQQException(Request $request, $qq_id)
  {
      $validator = Validator::make($request->all(), [
          'exception' => 'required|boolean',
      ]);
      if ($validator->fails()) {
          return $this->failure(-1, $validator->errors()->first());
      }
      $data = $request->only('exception');
      $qq = Qq::find($qq_id);
      if ($qq) {
          $qq->is_exception = $data['exception'];
          $qq->save();
          return $this->success(0, '更新成功', $qq);
      }
      return $this->failure(0, '没有找到QQ数据');
  }
  public function coverQQ(Request $request)
  {
      $deviceGroupAdd = DeviceGroupAdd::where('device_group_id',$request->device_group_id)->first();
      isset($request->cover_qq) && $deviceGroupAdd->cover_qq = $request->cover_qq;
      $deviceGroupAdd->save();
      return $this->success(0, '', $deviceGroupAdd);
  }

  public function listpage(Request $request)
  {
    $fans = Fans::where('type', $request->type)->get();
    return $this->success(0, '请求成功', $fans);
  }

  public function batchUpload(Request $request)
  {
    if ($request->hasFile('fans')) {
      $type = $request->type;
      if ($request->file('fans')->isValid()) {
        $path = $request->file('fans')->store('fans');
        $content = Storage::get($path);
        $n = 0;
        $data = [];
        if ($content) {
          $array = explode("\r\n", $content);
          $array = array_filter($array);
          $array_length = count($array);
          for ($i = 0; $i < $array_length; $i++) {
            $tempdata = explode('----', trim($array[$i]));
            $sex = '2';
            if(isset($tempdata[2])) {
              if($tempdata[2] == '女') {
                $sex = '0';
              } elseif($tempdata[2] == '男') {
                $sex = '1';
              }
            }
            $data[$n]['phone'] = $tempdata[0];
            $data[$n]['name'] = $tempdata[1];
            $data[$n]['sex'] = $sex;
            $data[$n]['type'] = $type; // 类型 1：微信；2：支付宝
            $data[$n]['created_at'] = date('Y-m-d H:i:s');
            $n++;
          }
          $count = count($data);
          if($count > 10000) {
            $splick_count = floor(count($data)/1000);
            if ($splick_count<= 0) $splick_count = 1;
            $new_arr = array_chunk($data, $splick_count);
            foreach ($new_arr as $item) {
              Fans::insertOnDuplicateKey($item);
            }
          } else {
            Fans::insertOnDuplicateKey($data);
          }
          return $this->success(0, '上传成功！');
        }
        return $this->failure(-1, '文件内容为空！');
      }
    }
    if ($request->hasFile('qq')) {
      if ($request->file('qq')->isValid()) {
          $path = $request->file('qq')->store('qq');
          $content = Storage::get($path);
          $n = 0;
          $data = [];
          if ($content) {
              $array = explode("\r\n", $content);
              $array = array_filter($array);
              $array_length = count($array);
              if($request->qq_group_id>0){
                  $qq_group_id = $request->qq_group_id;
                  $cover_qq = DeviceGroupAdd::where('device_group_id',$qq_group_id)->first()->cover_qq;
              }else{
                  $qq_group_id = null;
                  $cover_qq = 1;
              }
              if($cover_qq == 1){ //重置使用状态
                  if($qq_group_id > 0){
                      for ($i = 0; $i < $array_length; $i++) {
                          $tempdata = explode('----', trim($array[$i]));
                          $data[$n]['qq_num'] = $tempdata[0];
                          $data[$n]['qq_pwd'] = $tempdata[1];
                          $data[$n]['is_used'] = 0;
                          $data[$n]['error_password_num'] = 0;
                          $data[$n]['qq_group_id'] = $qq_group_id;
                          $data[$n]['created_at'] = date('Y-m-d H:i:s');
                          $n++;
                      }
                  }else{ //在'全部'中导入数据将刷新使用和异常为0
                      for ($i = 0; $i < $array_length; $i++) {
                          $tempdata = explode('----', trim($array[$i]));
                          $data[$n]['qq_num'] = $tempdata[0];
                          $data[$n]['qq_pwd'] = $tempdata[1];
                          $data[$n]['is_used'] = 0;
                          $data[$n]['is_exception'] = 0;
//                          $data[$n]['qq_group_id'] = $qq_group_id;//不改变分组，因此注释掉
                          $data[$n]['created_at'] = date('Y-m-d H:i:s');
                          $n++;
                      }
                  }
              }else{ //不重置使用状态
                  for ($i = 0; $i < $array_length; $i++) {
                      $tempdata = explode('----', trim($array[$i]));
                      $data[$n]['qq_num'] = $tempdata[0];
                      $data[$n]['qq_pwd'] = $tempdata[1];
                      $data[$n]['qq_group_id'] = $qq_group_id;
                      $data[$n]['created_at'] = date('Y-m-d H:i:s');
                      $n++;
                  }
              }
              $count = count($data);
              if($count > 10000) {
                  $splick_count = floor(count($data)/1000);
                  if ($splick_count<= 0) $splick_count = 1;
                  $new_arr = array_chunk($data, $splick_count);
                  foreach ($new_arr as $item) {
                      Qq::insertOnDuplicateKey($item);
                  }
              } else {
                  Qq::insertOnDuplicateKey($data);
              }
              return $this->success(0, '上传成功！');
          }
          return $this->failure(-1, '文件内容为空！');
      }
    }
      if ($request->hasFile('log_phone')) {
        if($request->type){
            $type = $request->type;
            if ($request->file('log_phone')->isValid()) {
                $path = $request->file('log_phone')->store('log_phone');
                $content = Storage::get($path);
                $n = 0;
                $data = [];
                if ($content) {
                    $array = explode("\r\n", $content);
                    $array = array_filter($array);
                    $array_length = count($array);
                    for ($i = 0; $i < $array_length; $i++) {
                        $tempdata = explode('----', trim($array[$i]));
                        $data[$n]['account'] = $tempdata[0];
                        $data[$n]['password'] = $tempdata[1];
                        $data[$n]['is_used'] = 0;
                        $data[$n]['type'] = $type;
                        $data[$n]['sign'] = $tempdata[2];
                        $data[$n]['created_at'] = date('Y-m-d H:i:s');
                        $data[$n]['updated_at'] = null;
                        $n++;
                    }
                    $count = count($data);
                    if($count > 10000) {
                        $splick_count = floor(count($data)/1000);
                        if ($splick_count<= 0) $splick_count = 1;
                        $new_arr = array_chunk($data, $splick_count);
                        foreach ($new_arr as $item) {
                            LogPhone::insertOnDuplicateKey($item);
                        }
                    } else {
                        LogPhone::insertOnDuplicateKey($data);
                    }
                    return $this->success(0, '上传成功！');
                }
                return $this->failure(-1, '文件内容为空！');
            }
        }
      }
    return $this->failure(-1, '没有上传任何文件！');
  }

  public function destroy($id)
  {
    Fans::destroy($id);
    return $this->success(0, '删除成功');
  }

  public function batchRemove(Request $request)
  {
    $ids = explode(',', $request->ids);
    Fans::destroy($ids);
    return $this->success(0, '删除成功');
  }

  public function export(Request $request)
  {
    if($request->token == '' || Cache::pull('pin'.$request->token) != $request->token) return 404;
    if(!$request->qq&&!$request->log_phone){
        $sex = $request->sex;
        $ext = '所有';
        $date = date('Y年m月d日');
        if($sex == 0){$ext = '女';}
        if($sex == 1){$ext = '男';}
        if(!$request->type){
            $type_name = '-';
            if($sex == -1){
                $fans = Fans::get();
            }else{
                $fans = Fans::where(['sex' => $sex])->get();
            }
        }else{
            $type = $request->type;
            $type_name = $type == 1 ? '微信' : '支付宝';
            if($sex == -1){
                $fans = Fans::where(['type' => $type])->get();
            }else{
                $fans = Fans::where(['sex' => $sex, 'type' => $type])->get();
            }
        }
        $filename = '粉丝数据-' . $date . $type_name . '-' . $ext . '.txt';
        $encoded_filename = urlencode($filename);
        $encoded_filename = str_replace("+", "%20", $encoded_filename);
        header("Content-Type: application/octet-stream");
        if (preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])) {
            header('Content-Disposition:  attachment; filename="' . $encoded_filename . '"');
        } elseif (preg_match("/Firefox/", $_SERVER['HTTP_USER_AGENT'])) {
            header('Content-Disposition: attachment; filename*="utf8' . $filename . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $filename . '"');
        }
        foreach ($fans as $fan) {
            if($fan['sex'] == 1) {
                $sex = '男';
            } elseif($fan['sex'] == 0) {
                $sex = '女';
            } else {
                $sex = '未知';
            }
            if($fan['type'] == 1) {
                $type = '微信';
            } elseif($fan['type'] == 2) {
                $type = '支付宝';
            } else {
                $type = '未知';
            }
            echo $fan['phone'] . '----' . $fan['name'] . '----' . $sex . '----' . $type . "\r\n";
        }
    }
    if($request->qq){
        $date = date('Y年m月d日');
        if($request->qq_group_id>0){
            $type = DeviceGroup::find($request->qq_group_id)->name;
            $query = Qq::where('qq_group_id',$request->qq_group_id);
            if($request->qq == -1){ $qq = $query->get(); $type .= '所有';}
            if($request->qq == 1){ $qq = $query->where('is_exception',0)->get(); $type .= '正常'; }
            if($request->qq == 2){ $qq = $query->where('is_exception',1)->get(); $type .= '异常'; }
            if($request->qq == 3){ $qq = $query->where(DB::raw("CHAR_LENGTH(phone_check)"), '>', 0)->get(); $type .= '手机验证'; }
        }else{
            $type = '所有';
            if($request->qq == -1){ $qq = Qq::get(); }
            if($request->qq == 1){ $qq = Qq::where('is_exception',0)->get();  $type = '正常'; }
            if($request->qq == 2){ $qq = Qq::where('is_exception',1)->get();  $type = '异常'; }
            if($request->qq == 3){ $qq = Qq::where(DB::raw("CHAR_LENGTH(phone_check)"), '>', 0)->get(); $type .= '手机验证'; }
        }
        $filename = $type . 'QQ数据-' . $date . '.txt';
        $encoded_filename = urlencode($filename);
        $encoded_filename = str_replace("+", "%20", $encoded_filename);
        header("Content-Type: application/octet-stream");
        if (preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])) {
            header('Content-Disposition:  attachment; filename="' . $encoded_filename . '"');
        } elseif (preg_match("/Firefox/", $_SERVER['HTTP_USER_AGENT'])) {
            header('Content-Disposition: attachment; filename*="utf8' . $filename . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $filename . '"');
        }
        if($request->qq == 3){ //手机验证数据特别导出
            foreach ($qq as $row) {
                echo $row['qq_num'] . '----' . $row['qq_pwd'] . '----' . $row['phone_check'] . "\r\n";
            }
        }else{
            foreach ($qq as $row) {
                echo $row['qq_num'] . '----' . $row['qq_pwd'] . '----' . $row['is_exception'] . "\r\n";
            }
        }
    }
      if($request->log_phone){
          $date = date('Y年m月d日');
        if($request->type){
            if($request->type == 1){
                $str = 'login_status';
                $type1 = '成功';
                $type2 = '失败';
            }else{
                $str = 'account_status';
                $type1 = '正常';
                $type2 = '风险';
            }
            if($request->log_phone == -1){ $log_phone = LogPhone::where('type',$request->type)->get(); $type = '所有'; }
            if($request->log_phone == 1){ $log_phone = LogPhone::where('type',$request->type)->where($str,1)->get();  $type = $type1; }
            if($request->log_phone == 2){ $log_phone = LogPhone::where('type',$request->type)->where($str,2)->get();  $type = $type2; }
            if($request->log_phone == 3){ $log_phone = LogPhone::where('type',$request->type)->where($str,0)->get();  $type = '未知'; }
            if($request->type == 1){
                $type .= '预登录账号';
            }else{
                $type .= '正式账号';
            }
            $filename = $type . $date . '.txt';
            $encoded_filename = urlencode($filename);
            $encoded_filename = str_replace("+", "%20", $encoded_filename);
            header("Content-Type: application/octet-stream");
            if (preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])) {
                header('Content-Disposition:  attachment; filename="' . $encoded_filename . '"');
            } elseif (preg_match("/Firefox/", $_SERVER['HTTP_USER_AGENT'])) {
                header('Content-Disposition: attachment; filename*="utf8' . $filename . '"');
            } else {
                header('Content-Disposition: attachment; filename="' . $filename . '"');
            }
            foreach ($log_phone as $row) {
                echo $row['account'] . '----' . $row['password'] . '----' . $row['sign'] . "\r\n";
            }
        }
      }
  }

  public function deleteAll(Request $request)
  {
    if($request->type){
        $type = $request->type;
        Fans::where('type', $type)->delete();
    }else{
        Fans::where('is_used', 0)->orwhere('is_used', 1)->delete();
    }
    return $this->success(0, '清空成功');
  }

  public function deleteAllQQ(Request $request)
  {
      if($request->device_group_id>0){
          Qq::where('qq_group_id',$request->device_group_id)->delete();
      }else{
          Qq::where('is_used', 0)->orwhere('is_used', 1)->delete();
      }
      return $this->success(0, '清空成功');
  }

  public function logPhone(Request $request){
      $validator = Validator::make($request->all(), [
          'id' => 'sometimes|required|exists:log_phones,id'
      ]);
      if ($validator->fails()) {
          return $this->failure(-1, $validator->errors()->first());
      }
      if($request->id){
          LogPhone::destroy($request->id);
          return $this->success(0, '删除成功');
      }
      if($request->type == 1){//pre-login
          $totalCount = LogPhone::where('type', 1)->count();
          $usedCount = LogPhone::where('type', 1)->where('is_used', true)->count();
          $logPhone = LogPhone::where('type', 1)
              ->where('account','like','%'. $request->account .'%')
              ->where('password','like','%'. $request->password .'%')
              ->paginate(10)
              ->toArray();
      }else{//official-login
          $totalCount = LogPhone::where('type', 2)->count();
          $usedCount = LogPhone::where('type', 2)->where('is_used', true)->count();
          $logPhone = LogPhone::where('type', 2)
              ->where('account','like','%'. $request->account .'%')
              ->where('password','like','%'. $request->password .'%')
              ->paginate(10)
              ->toArray();
      }
      $logPhone['totalCount'] = $totalCount;
      $logPhone['usedCount'] = $usedCount;
      return $this->success(0, '请求成功', $logPhone);
  }

    public function getLogPhone(Request $request){
        $validator = Validator::make($request->all(), [
            'device_id' => 'required|exists:devices,id',
            'type' => 'required'
        ]);
        if ($validator->fails()) {
            return $this->failure(-1, $validator->errors()->first());
        }if($request->type == 1){
            $logPhone = LogPhone::where('type', $request->type)
                ->where('is_used', 0)
                ->select('id','account','password','sign')
                ->first();
        }else{
            $logPhone = LogPhone::where(DB::raw("UNIX_TIMESTAMP(updated_at)"),'<=', time()-86400)
                ->where('type', $request->type)
                ->where('account_status', '<', 2)
                ->select('id','account','password','sign')
                ->orWhere(DB::raw("UNIX_TIMESTAMP(updated_at)"), null)
                ->where('type', $request->type)
                ->where('is_used', 0)
                ->where('account_status', '<', 2)
                ->select('id','account','password','sign')
                ->first();
        }
        if($logPhone){
            $logPhone->is_used = 1;
            $logPhone->updated_at = date('Y-m-d h:i:s',time());
            $logPhone->save();
        }else{
            return $this->failure(-1, 'no data');
            $logPhone = LogPhone::where('type', $request->type)->select('id')->get();
            foreach ($logPhone as $row){
                $data = LogPhone::findOrFail($row->id);
                $data->is_used = 0;
                $data->is_exception = 0;
                $data->save();
            }
            $logPhone = LogPhone::where('type', $request->type)->where('is_used', 0)->select('id','account','sign')->first();
            $logPhone->is_used = 1;
            $logPhone->save();
        }
        return $this->success(0, '请求成功', $logPhone);
    }

    public function setLogPhone(Request $request){
        $validator = Validator::make($request->all(), [
            'log_phone_id' => 'required|exists:log_phones,id',
            'login_status' => 'sometimes|required',
            'account_status' => 'sometimes|required'
        ]);
        if ($validator->fails()) {
            return $this->failure(-1, $validator->errors()->first());
        }
        $logPhone = LogPhone::where('id',$request->log_phone_id)->first();
        if($logPhone){
            if($request->login_status){
                $logPhone->login_status = $request->login_status;
                $logPhone->save();
                return $this->success(0, '更新成功', $logPhone);
            }
            if($request->account_status){
                $logPhone->account_status = $request->account_status;
                $logPhone->save();
                return $this->success(0, '更新成功', $logPhone);
            }
            return $this->failure(-1, '更新失败');
        }
    }

  public function deleteAllLogPhone(Request $request){
        if($request->type){
            LogPhone::where('type', $request->type)->delete();
        }
        return $this->success(0, '清空成功');
  }

  public function insertWechat(Request $request){
      $validator = Validator::make($request->all(), [
          'wechat_id' => 'required',
          'wechat_name' => 'required'
      ]);
      if ($validator->fails()) {
          return $this->failure(-1, $validator->errors()->first());
      }
      $repeat = WechatId::where('wechat_id',$request->wechat_id)->first();
      if($repeat){
          $repeat->repeat_count += 1;
          $repeat->save();
          return $this->failure(-1,'ID重复');
      }
      $wechat = new WechatId();
      $wechat->wechat_id = $request->wechat_id;
      $wechat->wechat_name = $request->wechat_name;
      $wechat->save();
      return $this->success(0,'更新成功');
  }

    public function wechatList(Request $request){
        $validator = Validator::make($request->all(), [
            'id' => 'sometimes|exists:wechat_ids,id'
        ]);
        if ($validator->fails()) {
            return $this->failure(-1, $validator->errors()->first());
        }
        if($request->id){
            WechatId::destroy($request->id);
            return $this->success(0, '删除成功');
        }
        $wechatList = WechatId::where('wechat_id','like','%'.$request->wechat_id.'%')
            ->where('wechat_name','like','%'.$request->wechat_name.'%')
            ->paginate(10)->toArray();
        $wechatList['totalCount'] = WechatId::count();
        return $this->success(0, '请求成功', $wechatList);
    }

    public function wechatListDelete(Request $request){
        WechatId::truncate();
        return $this->success(0, '清空成功');
    }
}
